﻿using MaxMind.GeoIP2;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GeoIpDemo
{
    public class GeoSericeImpByGeoLite2 : IGeoService
    {
        public Geo GetByIp(string ip, string language = "en")
        {
            using (var reader = new DatabaseReader("GeoLite2-City.mmdb"))
            {
                var cityResponse = reader.City(ip);

                // 读取国家代码
                var countryIsoCode = cityResponse.Country.IsoCode;
                // 读取国家名称
                var countryName = cityResponse.Country.Names[language];
                // 读取国家名称(中文显示)
                //var countryNameCN = cityResponse.Country.Names["zh-CN"];
                // 读取州(国外)/省(国内)名称
                var countrySpecificName = cityResponse.MostSpecificSubdivision.Names[language];
                // 读取州(国外)/省(国内)代码
                var countrySpecificIsoCode = cityResponse.MostSpecificSubdivision.IsoCode;
                // 读取城市名称
                var cityName = cityResponse.City.Names[language];
                // 读取邮政编码
                var cityPostalCode = cityResponse.Postal.Code;
                // 获取纬度
                var locationLatitude = cityResponse.Location.Latitude;
                // 获取经度
                var locationLongitude = cityResponse.Location.Longitude;
                //时区
                var timezone = cityResponse.Location.TimeZone;

                return new Geo
                {
                    CountryIsoCode = countryIsoCode,
                    CountryName = countryName,
                    CountrySpecificIsoCode = countrySpecificIsoCode,
                    CountrySpecificName = countrySpecificName,
                    CityName = cityName,
                    CityPostalCode = cityPostalCode,
                    LocationLatitude = locationLatitude,
                    LocationLongitude = locationLongitude,
                    Timezone = timezone,
                };
            }
        }
    }
}
